import {HomeworkItemWrapper, Wrapper} from "./style";
import {
    Button,
    DatePicker,
    Dropdown,
    Form,
    Input,
    MenuProps,
    message,
    Modal,
    Radio,
    RadioChangeEvent,
    Select,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
import blank from "@/static/imgs/courseContent/blank.png";
import {useContext, useEffect, useState} from "react";
import styled from "styled-components";
import {SmallDashOutlined, UploadOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
import {CourseContext} from "@/pages/TeacherCourseContent/context/CourseContext.ts";
import {addHomework, getHomework} from "@/api/teacher/homeworkApi.ts";
import {uploadFile} from "@/api/common/homeworkApi.ts";
import dayjs from "dayjs";


const Homework = () => {

    const courseContext = useContext(CourseContext)

    const navigate = useNavigate()

    const [homeworkList, setHomeworkList] = useState([])

    const initHomeworkList = () => {
        getHomework(courseContext).then(res => {
            setHomeworkList(res.data.data)
        })
    }

    useEffect(() => {
        initHomeworkList()
    }, [])

    const topBtnStyle = {
        backgroundColor: "#00ca90",
        borderColor: "#00ca90",
        color: "#fff",
        width: "144px",
        height: "36px",
        borderRadius: "20px",
    }
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        const params = {
            ...form.getFieldsValue(),
            courseId: courseContext,
            releaseTime: Date.parse(form.getFieldValue('releaseTime')),
            deadline: Date.parse(form.getFieldValue('endTime')),
            typeLabel: form.getFieldValue('label'),
            type: form.getFieldValue('type') == 1 ? '个人作业' : '小组作业',
            file: filePath
        }
        addHomework(params).then(() => {
            initHomeworkList()
        })
        setValue(1)
        setFile(undefined)
        form.resetFields();
        setIsModalOpen(false);

    };

    const handleCancel = () => {
        setValue(1)
        setFile(undefined)
        form.resetFields();
        setIsModalOpen(false);
        initHomeworkList()

    };

    const [form] = Form.useForm();

    const AddHomeWrapper = styled.div`
        .add-homework-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .homework {
            display: flex;
            justify-content: space-between;
        }
    `;

    const [file, setFile] = useState<UploadFile>();

    const [filePath, setFilePath] = useState('')

    const props: UploadProps = {
        maxCount: 1,
        name: 'file',
        beforeUpload(file) {
            handleUpload(file)
            setFile(file);
            return false;
        },
        fileList: file ? [file] : [],
    };

    const handleUpload = (file: UploadFile) => {
        if (!file) return
        const formData = new FormData()
        formData.append('filePath', '\\homework')
        formData.append('file', file as any)
        uploadFile(formData).then(res => {
            message.success('上传成功')
            setFilePath(res.data.data.filePath)
            console.log(res.data)
        })
    }

    const [value, setValue] = useState(1);

    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };


    const AddHomework = () => {
        return (
            <AddHomeWrapper>
                <Form
                    form={form}
                    name="basic"
                    autoComplete="off"
                >
                    <Form.Item
                        label="作业类型"
                        name="type"
                        rules={[{required: true, message: '请选择作业类型!'}]}
                    >
                        <Radio.Group defaultValue={1} onChange={onChange} value={value}>
                            <Radio value={1}>个人作业</Radio>
                            <Radio value={2}>小组作业</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="作业标题"
                        name="title"
                        rules={[{required: true, message: '请输入作业标题!'}]}
                    >
                        <Input placeholder={'作业标题'}/>
                    </Form.Item>
                    <div className='homework'>
                        <Form.Item
                            style={{flex: 2}}
                            label="作业描述"
                            name="description"
                        >
                            <Input.TextArea/>
                        </Form.Item>
                        <Upload style={{flex: 1}} {...props}>
                            <Button icon={<UploadOutlined/>}>Click to Upload</Button>
                        </Upload>
                    </div>

                    <Form.Item
                        label="活动类型标签"
                        name="label"
                        initialValue={"作业"}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        label="应用环节"
                        name="applyTime"
                    >
                        <Select
                            placeholder={'请选择'}
                            options={[
                                {value: '课前', label: '课前'},
                                {value: '课中', label: '课中'},
                                {value: '课后', label: '课后'},
                                {value: '期中', label: '期中'},
                                {value: '期末', label: '期末'},
                            ]}
                        />
                    </Form.Item>
                    <Form.Item
                        label="所属章节"
                        name="chapter"
                    >
                        <Select
                            placeholder={'请选择'}
                            options={[]}
                        />
                    </Form.Item>
                    <div className='add-homework-bottom'>
                        <Form.Item
                            label="发布时间"
                            name="releaseTime"
                            rules={[{required: true, message: '请选择发布时间!'}]}
                        >
                            <DatePicker
                                placeholder={'请选择发布时间'}
                                showTime
                                onChange={(value, dateString) => {
                                    console.log('Selected Time: ', value);
                                    console.log('Formatted Selected Time: ', dateString);
                                }}
                            />
                        </Form.Item>
                        <Form.Item
                            label="截止时间"
                            name="endTime"
                            rules={[{required: true, message: '请选择截止时间!'}]}
                        >
                            <DatePicker
                                placeholder={'请选择截止时间'}
                                showTime
                                onChange={(value, dateString) => {
                                    console.log('Selected Time: ', value);
                                    console.log('Formatted Selected Time: ', dateString);
                                }}
                            />
                        </Form.Item>
                    </div>
                </Form>
            </AddHomeWrapper>
        )
    }

    const HomeworkItem = ({
                              typeLabel,
                              title,
                              type,
                              deadline,
                              correctCounts,
                              noCorrectCounts,
                              noSubmitCounts,
                              homeworkId,
                          }: any) => {
        const items: MenuProps['items'] = [
            {
                label: <a>编辑</a>,
                key: '0',
            },
            {
                label: <a>移动到章节</a>,
                key: '1',
            }, {
                label: <a>保存到备课区</a>,
                key: '2',
            },
            {
                label: <a>删除</a>,
                key: '3',
            },
        ];
        return (
            <HomeworkItemWrapper>
                <div className="content">
                    <div className="left">
                        <img src="	https://www.ketangpai.com/images/web2x_zuoye.png" alt=""/>
                        <div className="another-name">
                            <span>{typeLabel}</span>
                        </div>
                    </div>
                    <div className="right">
                        <div className="info">
                            <div className="title" onClick={() => {
                                navigate('/teacherHomeworkDetail/' + courseContext + '/' + homeworkId)
                            }}>{title}
                            </div>
                            <div className="sub-bar">
                                <span>提交截止时间：{dayjs(deadline).format('YYYY/MM/DD HH:mm')}</span>
                                <div className="divider"></div>
                                <span>{type}</span>
                            </div>
                        </div>
                        <div className="function">
                            <div className="situation">
                                <div className="item-info">
                                    <i className='font-color--main'>{correctCounts}</i>
                                    <i className='pt-text'>已批完</i>
                                </div>
                                <div className="item-info">
                                    <i className='font-color--main'>{noCorrectCounts}</i>
                                    <i className='pt-text'>未批完</i>
                                </div>
                                <div className="item-info">
                                    <i className='font-color--main'>{noSubmitCounts}</i>
                                    <i className='pt-text'>未交</i>
                                </div>
                            </div>
                            <Dropdown menu={{items}} trigger={['click']}>
                                <div className="settings">
                                    <SmallDashOutlined style={{fontSize: '16px'}}/>
                                    <div>更多</div>
                                </div>
                            </Dropdown>
                        </div>
                    </div>
                </div>
            </HomeworkItemWrapper>
        )
    }


    return (
        <Wrapper>
            <Modal width={'700px'} title="添加作业" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                   cancelText={'取消'} okText={'确认'}>
                <AddHomework/>
            </Modal>
            <div className="top flex">
                <div className="left flex">
                    <div>共</div>
                    <div>{homeworkList.length}</div>
                    <div>个活动</div>
                </div>
                <div className="right">
                    <Button style={topBtnStyle} type="primary" onClick={showModal}>+ 添加作业</Button>
                </div>
            </div>
            <div className="content">
                <div className="homework-list">
                    {
                        homeworkList.map((item: any) => {
                            return <HomeworkItem {...item}/>
                        })
                    }
                </div>
                {
                    homeworkList.length === 0 && <div className="no-data">
                            <img src={blank} alt=""/>
                            <div>暂无数据</div>
                        </div>
                }
            </div>
        </Wrapper>
    )
}
export default Homework;